package com.jinzecloud.reportapproval.config;

import com.jinzecloud.reportapproval.filter.CustomAccessDeniedHandler;
import com.jinzecloud.reportapproval.filter.CustomAuthenticationEntryPoint;
import com.jinzecloud.reportapproval.filter.JwtRequestFilter;
import com.jinzecloud.reportapproval.utils.JwtUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Resource
	private JwtUtil jwtUtil;

	@Resource
	private UserDetailsService userDetailsService;

	@Resource
	private CustomAccessDeniedHandler customAccessDeniedHandler;

	@Resource
	private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.
				csrf().disable()
				.cors()
				.and()
				.authorizeRequests()
				.antMatchers("/admin/**").permitAll()
				.antMatchers("/download/**","/template/**" ,"/static/**").permitAll()
				.antMatchers("/v3/api-docs", "/upload/**", "/swagger-resources/**", "/swagger-ui/**", "/webjars/**").permitAll()
				.antMatchers("/reportapproval/instrument/uploadFile/**").permitAll()
				.anyRequest().authenticated()
				.and()
				.addFilterBefore(new JwtRequestFilter(userDetailsService, jwtUtil), UsernamePasswordAuthenticationFilter.class)
				.exceptionHandling()
				.accessDeniedHandler(customAccessDeniedHandler)
				.authenticationEntryPoint(customAuthenticationEntryPoint)
				.and().sessionManagement().maximumSessions(1)
		;
		// 禁用security
//		 http.authorizeRequests().anyRequest().permitAll().and().csrf().disable();
	}

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	@Override
	@Bean
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}
}
